(function () {
	
	//添加菜单，弹出弹窗
    jQuery('.addBtn').on('click', function () {
    		jQuery('#id').val('');
    		jQuery('#name').val('');
        jQuery('#describe').val('');
        jQuery('#Modal').modal('show');
    });

    //table数据显示
    var serverData = {};
    var	serverTable;
    
    //未绑定table数据显示
    var serverData1 = {};
    var	serverTable1;
    serverData1.templateId = '';
    serverData1.gradingId = '';
    
    
    //已绑定table数据显示
    var serverData2 = {};
    var	serverTable2;
    serverData2.templateId = '';
    serverData2.gradingId = '';
    
    
    var funnel;
    var funnelData = [];
    var funnelIndex = 0;
    
    var templateId = '';
    var gradingId = '';
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/template/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [{
	                data: null,
	                defaultContent: ""
            		},
                {
            			data: 'name'
                },
                {
                		data: 'describe'
                },
                {
                		data: 'createTime',
                		render: function(data, type, full, meta){
                			if(data){
                				return moment(data).format('YYYY/MM/DD HH:mm');
                			}else{
                				return '';
                			}
                    }
                },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate ='<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>';

                        return operate;

                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }
                templateId = "";
                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-remove')!=-1 || target.className.indexOf('delBtn')!=-1){
                        deleteInfo(data);
                    }else if(target.className.indexOf('fa-pencil')!=-1||target.className.indexOf('editBtn')!=-1){
                        editInfo(data);
                    }else{
	                    if($(this).hasClass('selected') ){
	            				$(this).removeClass('selected');
	            				gradingId = "";
	            				serverData1.gradingId = gradingId;
	            				serverData2.gradingId = gradingId;
	            				templateId = "";
	            				serverData1.templateId = templateId;
	        	    				serverData2.templateId = templateId;
	            			}else{
	            				serverTable.$('tr.selected').removeClass('selected');
	            	    			$(this).addClass('selected');
	            	    			templateId = data.id;
	            	    			serverData1.templateId = templateId;
	            	    			serverData2.templateId = templateId;
	            			}
	                    setGrading();
                    }
                    return;
                } );
            }
        });
        
        serverTable1 = jQuery('#dataTable1').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/template/getNotSetUser',
                "data": function (d) {
                    return $.extend({}, d, serverData1);
                }
            },
            columns: [{
	                data: null,
	                defaultContent: ""
        			},
        			{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="addDate"/>';
                        return operate;
                    }
    	        		},
                {
        				data: 'name'
                },
                {
                		data: 'hierarchy',
                		render: function(data, type, full, meta){
                			if(data){
                				return data.groupName;
                			}else{
                				return '';
                			}
                		}
                },
                {
                		data: 'grading',
                		render: function(data, type, full, meta){
                			if(data){
                				return data.gradingName;
                			}else{
                				return '';
                			}
                		}
                },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>';
                        return operate;

                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable1.off('click','tr');
                serverTable1.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable1.row( this ).data();

                    if(target.className.indexOf('fa-sign-in')!=-1||target.className.indexOf('addNode')!=-1){
                    		setUser(data,data.name);
                    }
                    return;
                } );
            }
        });
        
        serverTable2 = jQuery('#dataTable2').DataTable({
	        	"serverSide": true,
	        	"ordering": false,
	        	"ajax": {
	        		"dataType": "json",
	        		"type": "post",
	        		"cache": false,
	        		"url": window.rootPath+'/ui/template/getSetUser',
	        		"data": function (d) {
	        			return $.extend({}, d, serverData2);
	        		}
	        	},
	        	columns: [{
	        		data: null,
	        		defaultContent: ""
	        	},
	        	{
                data: 'id',
                render: function (data, type, full, meta) {
                    var operate ='<input type="checkbox" dataId="'+data+'" group="removeDate"/>';
                    return operate;
                }
        		},
	        	{
	        		data: 'name'
	        	},
	        	{
	        		data: 'hierarchy',
	        		render: function(data, type, full, meta){
	        			if(data){
	        				return data.groupName;
	        			}else{
	        				return '';
	        			}
	        		}
	        	},
	        	{
	        		data: 'grading',
	        		render: function(data, type, full, meta){
	        			if(data){
	        				return data.gradingName;
	        			}else{
	        				return '';
	        			}
	        		}
	        	},
	        	{
	        		data:null,
	        		defaultContent: "",
	        		render: function(data, type, full, meta){
	        			var operate = '<button type="button" class="btn btn-sm btn-info delBtn" title="移除"><i class="fa fa-remove"></i></button>';
	        			return operate;
	        			
	        		}
	        	}],
	        	"drawCallback": function ( oSettings ) {
	        		var k = 0;
	        		var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
	        		
	        		for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
	        		{
	        			$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
	        			k++;
	        		}
	        		
	        		serverTable2.off('click','tr');
	        		serverTable2.on( 'click', 'tr', function (event) {
	        			event=event||window.event;
	        			var target=event.target||event.scrElement;
	        			var data = serverTable2.row( this ).data();
	        			
	        			if(target.className.indexOf('fa-remove')!=-1 || target.className.indexOf('delBtn')!=-1){
	        				removeUser(data,data.name);
	        			}
	        			return;
	        		} );
	        	}
        });
        
        var deleteInfo=function(data){
            if(!data) return;
            $.springLemonDialog({
                content:'确认模块：'+data.name+'？',//确认文本
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+"/ui/template/delete/"+data.id;
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type : "post",
                            dataType:"json",
                            success:function(data){
                                serverTable.draw(false);
                                cleanDate();
                                message('删除信息成功!');
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }

            });

        };
        //编辑信息
        var editInfo=function(data){
            if(!data) return;
            jQuery('#id').val(data.id);
            jQuery('#name').val(data.name);
            jQuery('#describe').val(data.describe);
            jQuery('#Modal').modal('show');
        };
        
        //查询
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#search').val();
            serverTable.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn').on("click",function(){
            jQuery('#search').val('');
            serverData.key ='';
            serverTable.draw();
        });
        
        //查询
        jQuery('.searchBtn1').on('click',function(){
            serverData1.key=jQuery('#search1').val();
            serverTable1.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn1').on("click",function(){
            jQuery('#search1').val('');
            serverData1.key ='';
            serverTable1.draw();
        });
        //查询
        jQuery('.searchBtn2').on('click',function(){
        	serverData2.key=jQuery('#search2').val();
        	serverTable2.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn2').on("click",function(){
        	jQuery('#search2').val('');
        	serverData2.key ='';
        	serverTable2.draw();
        });
        
        //新增，编辑保存
        jQuery('.saveBtn').on('click',function(){
            if(jQuery("#modalForm") && !jQuery("#modalForm").Validform({tiptype:3, showAllError:true}).check(false)){
                return;
            };
            $("#right").mLoading("show");
            var data={
                    id:jQuery('#id').val(),
                    name:jQuery('#name').val(),
                    describe:jQuery('#describe').val(),
                };
            var url=window.rootPath+'/ui/template/save';
            jQuery.ajax({
                url:encodeURI(url),
                type:'post',
                data:JSON.stringify(data),
                dataType:'json',
                contentType:'application/json;charset=utf-8',
                success: function () {
                    jQuery('#Modal').modal('hide');
                    serverTable.draw(false);
                    cleanDate();
                    message('信息保存成功！');
                    $("#right").mLoading("hide");
                }
            });
        });
        
        function cleanDate(){
        	  	gradingId = "";
			serverData1.gradingId = gradingId;
			serverData2.gradingId = gradingId;
			templateId = "";
			serverData1.templateId = templateId;
			serverData2.templateId = templateId;
			setGrading();
        }
        
        funnel.on('click', function (params) {
        		gradingId = params.data.id;
	    		serverData1.gradingId = gradingId;
	    		serverData2.gradingId = gradingId;
	    		serverTable1.draw(false);
	    		serverTable2.draw(false);
	    		showDownplay(funnelIndex);
	    		funnelIndex = params.dataIndex;
	    		showHighlight(funnelIndex);
        });
        
        function setUser(data,name){
	    		if(gradingId == ''){
	    			message('请选择需要绑定的评分区域!');
	    			return;
	    		}
	        $.springLemonDialog({
	            title:'系统提示',//标题   默认为   系统提示
	            content:'是否要绑定'+name+'？',//确认文本
	            bootstrapModalOption:{keyboard: true},
	            clickButton:function(sender,modal,index){//按钮事件处理
	                //index:0 确认    1：取消
	                //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
	            		$("#right").mLoading("show");
	                if(index==0){
	                    var url=window.rootPath+'/ui/template/addUser/'+templateId+'/'+gradingId+'/'+data.id;
	                    jQuery.ajax({
	                        url:encodeURI(url),
	                        cache:false,
	                        type :"post",
	                        data: '',
	                        dataType:"json",
	                        contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	                        success:function(data){
	                        		message(data.msg);
	                            serverTable1.draw(false);
	                            serverTable2.draw(false);
	                            $("#right").mLoading("hide");
	                        }
	                    });
	                }
	                $(this).closeDialog(modal);
	            }
	        });
	    }
        
        function removeUser(data,name){
	        	$.springLemonDialog({
	        		title:'系统提示',//标题   默认为   系统提示
	        		content:'是否要移除'+name+'？',//确认文本
	        		bootstrapModalOption:{keyboard: true},
	        		clickButton:function(sender,modal,index){//按钮事件处理
	        			//index:0 确认    1：取消
	        			//sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
	        			$("#right").mLoading("show");
	        			if(index==0){
	        				var url=window.rootPath+'/ui/template/removeUser/'+templateId+'/'+gradingId+'/'+data.id;
	        				jQuery.ajax({
	        					url:encodeURI(url),
	        					cache:false,
	        					type :"post",
	        					data: '',
	        					dataType:"json",
	        					contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	        					success:function(data){
	        						message(data.msg);
	        						serverTable1.draw(false);
	        						serverTable2.draw(false);
	        						$("#right").mLoading("hide");
	        					}
	        				});
	        			}
	        			$(this).closeDialog(modal);
	        		}
	        	});
        }
        
        //未绑定 全选
        $("#allNotBound").click(function() {
        		var addDate = $(":checkbox[group=addDate]");
            if ($(this).prop("checked")) {
            		addDate.each(function() {
                    $(this).prop("checked", true);  
                });  
            } else {  
            		addDate.each(function() {  
                    $(this).prop("checked", false);  
                });  
            }  
        }); 
        
        //已绑定 全选
        $("#allBound").click(function() {
    	    	var removeDate = $(":checkbox[group=removeDate]");
    	    	if ($(this).prop("checked")) {
    	    		removeDate.each(function() {
    	    			$(this).prop("checked", true);  
    	    		});  
    	    	} else {  
    	    		removeDate.each(function() {  
    	    			$(this).prop("checked", false);  
    	    		});  
    	    	}  
        }); 
        
        //获取全选数据
        function getSelectData(group){
        		var obj = $(":checkbox[group="+group+"]:checked");
        		var myArray = new Array();
        		var i =0;
        		obj.each(function() {
        			myArray[i++] = $(this).attr('dataId');
        		});
        		return myArray;
        }
        
        //绑定全部信息
        jQuery('.addUserBtn').on('click', function() {
	    		var id = gradingId;
	    		if(id == '' || id == '0'){
	    			message("请选择评分层级!");
	    			return;
	    		}
	    	    	var dataInfo = getSelectData('addDate');
	    	    	if(dataInfo.length == 0){
	    	    		message('请选择需要绑定的人员信息!');
	    			return;
	    	    	}
	    	    	$("#right").mLoading("show");
	    	    	var d = {"dataInfo" : dataInfo};
	    	    	
	    	    	var url = window.rootPath +'/ui/template/addUserAll/'+templateId+'/'+gradingId;
            jQuery.ajax({
                url:encodeURI(url),
                cache:false,
                type :"post",
                data: JSON.stringify(d),
                dataType:"json",
                contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                success:function(data){
	            		$("#allNotBound").prop("checked", false); 
	            		$("#allBound").prop("checked", false); 
	    				message(data.msg);
	    				serverTable1.draw(false);
	    				serverTable2.draw(false);
	    				$("#right").mLoading("hide");
                }
            });
        });
        
        //移除全部信息
        jQuery('.deleteUserBtn').on('click', function() {
        		var dataInfo = getSelectData('removeDate');
	    		if(dataInfo.length == 0){
	    			message('请选择需要移除的人员信息!');
	    			return;
	    		}
	    		$("#right").mLoading("show");
	    	    	var d = {
	    	    			"dataInfo" : dataInfo
	    	    		};
	    	    	var url = window.rootPath +'/ui/template/removeUserAll/'+templateId+'/'+gradingId;
	    	    	jQuery.ajax({
	    	    		url:encodeURI(url),
	    	    		cache:false,
	    	    		type :"post",
	    	    		data: JSON.stringify(d),
	    	    		dataType:"json",
	    	    		contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	    	    		success:function(data){
	    	    			$("#allNotBound").prop("checked", false); 
                		$("#allBound").prop("checked", false); 
	    	    			message(data.msg);
	    	    			serverTable1.draw(false);
	    				serverTable2.draw(false);
	    				$("#right").mLoading("hide");
	    	    		}
	    	    	});
        });
        
        
        jQuery('.gradingBtn').on('click',function(){
        		if(templateId == ''){
        			message('请选择模板信息！');
        			return;
        		}
        		if($(this).hasClass('active')){
        			var name = $(this).text();
        			var id = $(this).attr('id');
                $.springLemonDialog({
                    content:'确认移除'+name+'及绑定该层级人员？',//确认文本
                    clickButton:function(sender,modal,index){//按钮事件处理
                        //index:0 确认    1：取消
                        //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                        if(index==0){
                        		$("#right").mLoading("show");
                        		var url=window.rootPath+'/ui/template/deleteGrading/'+templateId+'/'+id;
                    			jQuery.ajax({
								url:encodeURI(url),
								type:'post',
								data:'',
								dataType:'json',
								contentType:'application/json;charset=utf-8',
								success: function (data) {
									deleteArr(funnelData,id);
									var data = reSetSortNum(funnelData);
									updateFunnel(data);
									$('#'+id).removeClass('active');
		            					serverTable1.draw(false);
		            					serverTable2.draw(false);
		            					message('移除成功！');
		            					$("#right").mLoading("hide");
								}
                    			});
	                    		
                        }
                        $(this).closeDialog(modal);
                    }

                });
        			
        		}else{
            		if(hasLevel($(this).attr('level'),funnelData)){
            			message('已存在相同等级的层级信息，不能添加<'+$(this).text()+'>此层级！');
            			return;
            		}
            		$("#right").mLoading("show");
        			$(this).addClass('active');
        			var item = {};
            		item.name = $(this).text();
            		item.value = $(this).attr('level');
            		item.id = $(this).attr('id');
            		
            		var url=window.rootPath+'/ui/template/addGrading/'+templateId+'/'+item.id;
                jQuery.ajax({
                		url:encodeURI(url),
            			type:'post',
            			data:'',
            			dataType:'json',
            			contentType:'application/json;charset=utf-8',
            			success: function (data) {
            				funnelData.push(item);
            				bubbleSort(funnelData);
            				var data = reSetSortNum(funnelData);
            				updateFunnel(data);
            				$("#right").mLoading("hide");
            			}
                });
				
        		}
        })
        
    });
    //判断是否存在相同层级信息
	function hasLevel(value,arr){
		var len = arr.length;
		for (var i = 0; i < len; i++) {
            if (arr[i].value == value) {//存在相同等级层级
            		return true;
            }
        }
    		return false;
    }
    //冒泡排序
    function bubbleSort(arr) {
        var len = arr.length;
        for (var i = 0; i < len; i++) {
            for (var j = 0; j < len - 1 - i; j++) {
                if (arr[j].value > arr[j+1].value) {        //相邻元素两两对比
                    var temp = arr[j+1];        //元素交换
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    }
    //重新设置排序号
    function reSetSortNum(arr){
    		var newObject = jQuery.extend(true, [], arr);
    		var len = newObject.length;
    		for(var i=0;i<len;i++){
    			newObject[i].value = i+1;
    		}
    		return newObject;
    }
    //更新数据
    function updateFunnel(data){
	    	funnel.setOption({
	    		series:{
	    			max:data.length,
	    			data :data
	    		}
	    	});
    }
    
    //移除数据
    function deleteArr(arr,value){
	    	for (var i =  0; i < arr.length; i++){
	    		if(arr[i].id == value){
	    			arr.splice(i,1);
	    		}
	    	}
	    	return arr;
    }
    
    //评分层级数据
    function setGrading(){
    		jQuery('.gradingBtn').removeClass('active');
    		serverTable1.draw(false);
    		serverTable2.draw(false);
    		//清空评分层级数据
    		funnelData = [];
		updateFunnel(funnelData);
    		if(templateId == ''){
    			return;
    		}else{
    			var url=window.rootPath+'/ui/template/getGrading/'+templateId;
            jQuery.ajax({
            		url:encodeURI(url),
        			type:'post',
        			data:'',
        			dataType:'json',
        			contentType:'application/json;charset=utf-8',
        			success: function (data) {
        				var gradings = data.gradings;
        				if(gradings.length > 0){
	        				for(var i=0;i<gradings.length;i++){
	        					$('#'+gradings[i].id).addClass('active');
	                			var item = {};
	                    		item.name = gradings[i].gradingName;
	                    		item.value = gradings[i].gradingLevel.extended1;
	                    		item.id = gradings[i].id;
	                    		funnelData.push(item);
	        				}
	        				
	        				bubbleSort(funnelData);
	        				var data = reSetSortNum(funnelData);
	        				updateFunnel(data);
        				}
        			}
            });
    		}
    		
    }
    
    
  //funnel demo
    funnel = echarts.init(document.getElementById('funnel'));
    
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}"
        },
        calculable: false,
        series: [{
            name: '评分层级',
            type: 'funnel',
            left: '1%',
            bottom: '5%',
            //x2: 80,

            width: '98%',
            //height: {totalHeight} - y - y2,
            min: 0,
            max: 1,
            minSize: '0%',
            maxSize: '100%',
            sort: 'ascending',//ascending descending
            gap: 2,
            label: {
                normal: {
                    show: true,
                    position: 'inside'
                },
                emphasis: {
                    textStyle: {
                        fontSize: 18
                    }
                }
            },
            labelLine: {
                normal: {
                    length: 10,
                    lineStyle: {
                        width: 1,
                        type: 'solid'
                    }
                }
            },
            itemStyle: {
                normal: {//正常情况显示
                    borderColor: '#fff',
                    borderWidth: 1
                },
            emphasis:{//高亮情况显示
                borderColor: '#f00',
                borderWidth: 4,
                }
            },
            data: ''

        }]
    };
    
    funnel.setOption(option);
    
    function showDownplay(index){
	    // 取消之前高亮的图形
	    funnel.dispatchAction({
	        type: 'downplay',
	        seriesIndex: 0,
	        dataIndex: index
	    });
    }
    
    function showHighlight(index){
	    // 高亮当前图形
	    funnel.dispatchAction({
	        type: 'highlight',
	        seriesIndex: 0,
	        dataIndex: index
	    });
    }

})();